package com.histone.lilian.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.histone.lilian.domain.entity.SysMenu;
import com.histone.lilian.domain.vo.MetaVo;
import com.histone.lilian.domain.vo.RouterVo;
import com.histone.lilian.mapper.SysMenuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.ssssssss.magicapi.model.ApiInfo;
import org.ssssssss.magicapi.model.Group;
import org.ssssssss.magicapi.provider.MagicAPIService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysMenuService {

    private final MagicAPIService magicAPIService;
    
    public static final String PERMISSION_STRING = "perms[\"{0}\"]";
    /** 菜单类型（目录） */
    public static final String TYPE_DIR = "M";

    /** 菜单类型（菜单） */
    public static final String TYPE_MENU = "C";

    /** 菜单类型（按钮） */
    public static final String TYPE_BUTTON = "F";

    public SysMenuService(MagicAPIService magicAPIService) {
        this.magicAPIService = magicAPIService;
    }

    public List<RouterVo> magicBuildMenus(List<Map<String, Object>> menuList) {
        List<SysMenu> sysMenuList = menuList.stream().map(map ->
                BeanUtil.fillBeanWithMap(map, new SysMenu(), true)
        ).collect(Collectors.toList());
        return buildMenus(sysMenuList);
    }

    public void saveApi(List<Map<String, Object>> params) {

        params.forEach(map -> {
            try {
                String tableComment = StrUtil.removeSuffix(MapUtil.getStr(map, "tableComment"), "表");
                String tableName = MapUtil.getStr(map, "tableName");
                String tableNameSimple = StrUtil.removePrefix(tableName, "sys_");

                Group group = new Group();
                group.setName(tableComment);
                group.setType("1");
                group.setPath("");
                group.setParentId("6272230ddbbb43238d3734024c88d4a3");
                String groupId = magicAPIService.createGroup(group);
                // 查
                ApiInfo apiInfo = new ApiInfo();
                apiInfo.setMethod("GET");
                apiInfo.setLock("0");
                apiInfo.setOption(StrUtil.format("[{\"name\":\"permission\",\"value\":\"{}\",\"description\":\"允许拥有该权限的访问\"}]", tableName + ":page"));
                apiInfo.setPath(tableNameSimple);
                apiInfo.setName(tableComment + "列表");
                apiInfo.setGroupId(groupId);
                apiInfo.setScript(StrUtil.format("return db.table(\"{}\").page();", tableName));
                magicAPIService.saveApi(apiInfo);

                // 增
                apiInfo = new ApiInfo();
                apiInfo.setMethod("POST");
                apiInfo.setOption(StrUtil.format("[{\"name\":\"permission\",\"value\":\"{}\",\"description\":\"允许拥有该权限的访问\"}]", tableName + ":add"));
                apiInfo.setPath(tableNameSimple);
                apiInfo.setName(tableComment + "新增");
                apiInfo.setGroupId(groupId);
                apiInfo.setScript(StrUtil.format("return db.table(\"{}\").primary(\"{}_id\").save(body);", tableName, tableNameSimple));
                magicAPIService.saveApi(apiInfo);

                // 删
                apiInfo = new ApiInfo();
                apiInfo.setMethod("DELETE");
                apiInfo.setOption(StrUtil.format("[{\"name\":\"permission\",\"value\":\"{}\",\"description\":\"允许拥有该权限的访问\"}]", tableName + ":delete"));
                apiInfo.setPath(tableNameSimple + "{id}");
                apiInfo.setName(tableComment + "删除");
                apiInfo.setGroupId(groupId);
                apiInfo.setScript(StrUtil.format("return db.table(\"{}\").where().eq(\"{}_id\", id).delete();", tableName, tableNameSimple));
                magicAPIService.saveApi(apiInfo);

                // 改
                apiInfo = new ApiInfo();
                apiInfo.setMethod("PUT");
                apiInfo.setOption(StrUtil.format("[{\"name\":\"permission\",\"value\":\"{}\",\"description\":\"允许拥有该权限的访问\"}]", tableName + ":update"));
                apiInfo.setPath(tableNameSimple);
                apiInfo.setName(tableComment + "列表");
                apiInfo.setGroupId(groupId);
                apiInfo.setScript(StrUtil.format("return db.table(\"{}\").primary(\"{}_id\").save(body);", tableName, tableNameSimple));
                magicAPIService.saveApi(apiInfo);
                
            } catch (Exception e) {
                Console.log(e.getMessage());
            }
        });
    }

    public List<Tree<Long>> magicRouters(List<Map<String, Object>> menuList) {
        List<TreeNode<Long>> nodeList = CollUtil.newArrayList();

        menuList.forEach(map -> {
            SysMenu menu = BeanUtil.fillBeanWithMap(map, new SysMenu(), true, true);
            TreeNode<Long> treeNode = new TreeNode<>(menu.getMenuId(), menu.getParentId(), getRouteName(menu), menu.getOrderNum());

            Dict meta = Dict.create()
                    .set("title", menu.getMenuName())
                    .set("icon", menu.getIcon())
                    .set("noCache", "1".equals(menu.getIsCache()))
                    .set("link", menu.getPath());

            Dict extra = Dict.create()
                    .set("hidden", "1".equals(menu.getVisible()))
                    .set("path", getRouterPath(menu))
                    .set("component", getComponent(menu))
                    .set("query", menu.getQuery())
                    .set("meta", meta);
            treeNode.setExtra(extra);

            nodeList.add(treeNode);
        });

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setWeightKey("orderNum");

        List<Tree<Long>> result = TreeUtil.build(nodeList, 0L);
        return result;
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */

    public List<RouterVo> buildMenus(List<SysMenu> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getParentId().intValue() == 0 && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/inner");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = StringUtils.replaceEach(menu.getPath(), new String[] { "http://", "https://" }, new String[] { "", "" });
                children.setPath(routerPath);
                children.setComponent("InnerLink");
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            routerPath = StringUtils.replaceEach(routerPath, new String[] { "http://", "https://" }, new String[] { "", "" });
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && TYPE_DIR.equals(menu.getMenuType())
                && "1".equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu)
    {
        String component = "Layout";
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            component = "InnerLink";
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = "ParentView";
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu)
    {
        return menu.getParentId().intValue() == 0 && TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals("1");
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu)
    {
        return menu.getIsFrame().equals("1") && menu.getPath().toLowerCase().startsWith("http");
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu)
    {
        return menu.getParentId().intValue() != 0 && TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}

